function imean = fsb_calculate_mean(idat,is_nan)

% FSB: Calculate mean image over 4th dimension while ignoring parts where the image is zero
% if so desired
%
% EXAMPLE:
% imean = fsb_calculate_mean(idat)
%
% INPUT:
% idat: 4-D image data
% is_nan:  arbitrary number, enter this argument if you want to ignore NaNs
%
% OUTPUT:
% imean: Average image file
%
% CALLED BY:
% FSB.m
%
% NOTES:
% Trying to do calculations in native space to speed up processing
%
% Copyright 2010 MPI for Biological Cybernetics
% Author: Steffen Stoewer
% License:GNU GPL, no express or implied warranties
% 
% $Revision 1.0
%
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

if nargin>1

    idat = single(idat); % idat needs to be converted to singles for NaN processing

    % Set parts of the image where the values are zero to NaN
    idat(idat==0) = NaN;

    % Find NaNs and set them to zero
    nans = isnan(idat);
    idat(nans) = 0;

    % Count up non-NaNs.
    n = sum(~nans,4);
    n(n==0) = NaN; % prevent divideByZero warnings

    % Sum up non-NaNs, and divide by the number of non-NaNs.
    imean = sum(idat,4) ./ n;

else

    imean = mean(idat,4);% calculate average brain

end

end
